import axios from 'axios'
import { Message } from 'element-ui'

// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 30000 // request timeout
})

service.interceptors.request.use(
  (config) => {
    // do something before request is sent
    if (!config.data) {
      config.data = {}
    }
    // const method = config.method.toUpperCase()
    // switch (method) {
    //   case 'PUT':
    //   case 'DELETE':
    //     config.data._method = method // 伪造方法
    //     config.method = 'post'
    //     break
    // }
    return config
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    const res = response.data
    return res
  },
  (error) => {
    console.log(`err${error}`) // for debug
    Message({
      message: '服务器出错，请重试',
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
